/*
 * @(#) PartInterService.java 2013-8-6 下午1:22:14
 *
 * Copyright 2013 Rockwell Automation, Inc. All rights reserved.
 * Rockwell Automation PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */package com.osi.mes.inter.erp;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;

import pnuts.lang.Context;

import com.datasweep.compatibility.client.Part;
import com.datasweep.compatibility.client.PartFilter;
import com.datasweep.compatibility.client.Response;
import com.datasweep.compatibility.pnuts.Functions;
import com.osi.mes.inter.BaseInterService;
import com.osi.mes.pm.PMService;
import com.rockwell.ftpc.framework.common.XMLUtils;
import com.rockwell.ftpc.framework.common.XmlData;
import com.rockwell.mes.rtmis.middle.constants.IMDConstants;
import com.rockwell.transactiongrouping.UserTransaction;

public class PartInterService extends BaseInterService
{

	private static PartInterService instatnce = null;
	private static PMService pmService = null;

	private PartInterService(Context context)
	{
		super(context);
	}

	private PartInterService(Functions functions)
	{
		super(functions);
	}

	public static PartInterService getInstance(Context context)
	{
		if (instatnce == null)
		{
			synchronized (PartInterService.class)
			{
				if (instatnce == null)
				{
					instatnce = new PartInterService(context);
					pmService = new PMService(context);
				}
			}
		}
		return instatnce;
	}

	public Hashtable<String, Object> receivePart(Hashtable receivedData)
	{
		UserTransaction ut = null;
		Hashtable<String, Object> returnValue = new Hashtable<String, Object>();
		try
		{
			Response r = getFunctions().getUserTransaction();
			ut = (UserTransaction) r.getResult();
			ut.setTransactionTimeout(120);
			ut.begin();
			String msgObjType = (String) receivedData.get(IMDConstants.MD_TABLE_COULMN_MSGObJ_TYPE);
			if (!"4".equals(msgObjType))
			{
				throw new Exception(
					"The MSGObjType value does not matched, it should be 4 instead of "
						+ msgObjType);
			}
			String msgTransType = (String) receivedData
				.get(IMDConstants.MD_TABLE_COULMN_MSG_TRANS_TYPE);

			String msgKeyFields = (String) receivedData
				.get(IMDConstants.MD_TABLE_COULMN_MSG_KEY_FIELDS);
			String msgFieldsValue = (String) receivedData
				.get(IMDConstants.MD_TABLE_COULMN_MSG_FIELDS_VALUE);
			String msgContent = (String) receivedData.get(IMDConstants.MD_TABLE_COULMN_MSG_CONTENT);
			XmlData xmlData = XMLUtils.strToXMLData(msgContent);
			Hashtable<String, ArrayList<Object>> value = xmlData.getData();

			PartFilter partFilter = getFunctions().createPartFilter();
			int docEntry = toInteger(msgFieldsValue);
			partFilter.forUdaEqualTo(
				UDA_PART_DOCENTRY, docEntry);
			Vector parts = getFunctions().getFilteredParts(
				partFilter);

			if (INTER_STR_CREATE.equalsIgnoreCase(msgTransType))
			{
				if (parts != null && parts.size() > 0)
				{
					throw new Exception(
						"The part object has already existed in RTMIS, the DocEntry is " + docEntry);
				}
				Part part = getFunctions().createPart();
				part.setUDA(
					INTER_CREATE, UDA_INTER_FLAG_SAP);
				saveHashtableToPartObject(
					part, value);
				pmService.sendPartToWMS(part, 0);
				
			}
			else if (INTER_STR_UPDATE.equalsIgnoreCase(msgTransType))
			{
				if (parts == null || parts.size() == 0)
				{
					throw new Exception("The part object did not exist in RTMIS, the DocEntry is "
						+ docEntry);
				}
				Part part = (Part) parts.get(0);
				part.setUDA(
					INTER_UPDATE, UDA_INTER_FLAG_SAP);
				saveHashtableToPartObject(
					part, value);
				pmService.sendPartToWMS(part, 1);
			}
			else if (INTER_STR_DELETE.equalsIgnoreCase(msgTransType))
			{
				if (parts == null || parts.size() == 0)
				{
					throw new Exception("The part object did not exist in RTMIS, the DocEntry is "
						+ docEntry);
				}
				Part part = (Part) parts.get(0);
				part.setUDA(
					INTER_DELETE, UDA_INTER_FLAG_SAP);
				Response response = part.save();
				if (response.isError())
				{
					throw new Exception(response.getFirstErrorMessage());
				}
				pmService.sendPartToWMS(part, 2);
			}
			else
			{
				throw new Exception("The operation type is error.");
			}

			returnValue.put(
				IMDConstants.RESPONSE_STATUS, IMDConstants.RESPONSE_STATUS_SUCCESSFUL);
			ut.commit();
		}
		catch (Exception e)
		{
			returnValue.put(
				IMDConstants.RESPONSE_STATUS, IMDConstants.RESPONSE_STATUS_FAILED);
			returnValue.put(
				IMDConstants.RESPONSE_LAST_ERR_MSG, e.getMessage());
			ut.rollback();
		}
		return returnValue;
	}

	private void saveHashtableToPartObject(Part part, Hashtable<String, ArrayList<Object>> value)
		throws Exception
	{
		part.setPartNumber(getTransferValue(
			value, "ItemCode"));
		part.setPartRevision("1");
		part.setDescription(getTransferValue(
			value, "ItemName"));
		part.setUnitOfMeasure(getTransferValue(
			value, "InventryUnit"));
		part.setUDA(
			getTransferValue(
				value, "ItmsGrpCod"), UDA_PART_ITEM_GROUP_NAME);
		part.setUDA(
			getTransferValue(
				value, "Class2"), UDA_PART_TYPE);
		part.setUDA(
			toInteger(getTransferValue(
				value, "DocEntry")), UDA_PART_DOCENTRY);
		part.setUDA(
			toInteger(getTransferValue(
				value, "ValidDays")), UDA_PART_VALID_PERIOD);
		part.setUDA(
			toFloat(getTransferValue(
				value, "MinLevel")), UDA_PART_MIN_LEVEL);
		part.setUDA(
			toFloat(getTransferValue(
				value, "MaxLevel")), UDA_PART_MAX_LEVEL);
		part.setUDA(
			toFloat(getTransferValue(
				value, "Weight")), UDA_PART_WEIGHT);
		part.setUDA(
			getTransferValue(
				value, "Spec"), UDA_PART_SPEC);
		part.setUDA(
			getTransferValue(
				value, "Class1"), UDA_PART_CLASS1);
		part.setUDA(
			getTransferValue(
				value, "Class2"), UDA_PART_CLASS2);
		part.setUDA(
			getTransferValue(
				value, "Class3"), UDA_PART_CLASS3);
		part.setUDA(
			getTransferValue(
				value, "Class4"), UDA_PART_CLASS4);
		part.setUDA(
			getTransferValue(
				value, "Class5"), UDA_PART_CLASS5);
		part.setUDA(
			getTransferValue(
				value, "ManageBatch"), UDA_PART_MANAGE_BATCH);
		part.setUDA(
			toFloat(getTransferValue(
				value, "AvgPrice")), UDA_PART_AVG_PRICE);

		Response response = part.save();
		if (response.isError())
		{
			throw new Exception(response.getFirstErrorMessage());
		}
	}

}
